package com.company.dcm.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.dcm.common.R;
import com.company.dcm.constant.RoleConstant;
import com.company.dcm.entity.Factory;
import com.company.dcm.entity.Permission;
import com.company.dcm.entity.User;
import com.company.dcm.entity.WorkShop;
import com.company.dcm.service.FactoryService;
import com.company.dcm.service.PermissionService;
import com.company.dcm.service.UserService;
import com.company.dcm.service.WorkShopService;
import com.company.dcm.utils.IdUtils;
import com.company.dcm.utils.StringUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private FactoryService factoryService;
    @Autowired
    private WorkShopService workShopService;
    @Autowired
    private UserService userService;
    @SaCheckRole(value = {RoleConstant.FACTORY_MANAGER,RoleConstant.BOSS},mode = SaMode.OR)
    @PostMapping("/setPermission")
    public R setPermission(@RequestBody Permission permission){
//        if((StringUtils.isNullOrEmpty(permission.getFactoryName())&&StringUtils.isNullOrEmpty(permission.getName()))
//        |StringUtils.isNullOrEmpty(permission.getUserName()))return R.error("参数不全！");
//
//        permission.setPermissionId(IdUtils.getInstance().NextId());
//
//        User user = userService.getExistByUserName(permission.getUserName());
//
//        if(!StringUtils.isNullOrEmpty(permission.getFactoryName())){
//            user.setRoleId(RoleConstant.FACTORY_MANAGER_INT);
//            userService.updateById(user);
//
//            permission.setFactoryId(factoryService.getBaseMapper().selectOne(new LambdaQueryWrapper<Factory>()
//                    .eq(Factory::getFactoryName,permission.getFactoryName())).getFactoryId());
//
//            permission.setUserId(user.getUserId());
//            if(permissionService.save(permission))return R.success("新增成功！");
//        }else if(!StringUtils.isNullOrEmpty(permission.getName())){
//            user.setRoleId(RoleConstant.WORKSHOP_MANAGER_INT);
//            userService.updateById(user);
//            User userNow = userService.getExistByUserName((String) StpUtil.getLoginId());
//            Long factoryId = permissionService.getFactoryIdsByUserId(userNow.getUserId()).get(0);
//            permission.setId(workShopService.getBaseMapper().selectOne(new LambdaQueryWrapper<WorkShop>()
//                    .eq(WorkShop::getFactoryId,factoryId)
//                    .eq(WorkShop::getName,permission.getName()))
//                    .getId());
//            permission.setUserId(user.getUserId());
//            if(permissionService.save(permission))return R.success("新增成功！");
//        }
//
//        return R.error("未知错误！");
        if((permission.getFactoryId()==null&&permission.getId()==null)
        |StringUtils.isNullOrEmpty(permission.getUserName()))return R.error("参数不全！");

        permission.setPermissionId(IdUtils.getInstance().NextId());

        User user = userService.getExistByUserName(permission.getUserName());

        if(permission.getFactoryId()!=null){
            if(permissionService.count(new LambdaQueryWrapper<Permission>()
                    .eq(Permission::getUserId,user.getUserId())
                    .eq(Permission::getFactoryId,permission.getFactoryId()))>0)return R.error("不可重复授权！");
            user.setRoleId(RoleConstant.FACTORY_MANAGER_INT);
            userService.updateById(user);
            permission.setUserId(user.getUserId());
            if(permissionService.save(permission))return R.success("新增成功！");

        }else if(permission.getId()!=null){
            if(permissionService.count(new LambdaQueryWrapper<Permission>()
                    .eq(Permission::getUserId,user.getUserId())
                    .eq(Permission::getId,permission.getId()))>0)return R.error("不可重复授权！");
            user.setRoleId(RoleConstant.WORKSHOP_MANAGER_INT);
            userService.updateById(user);
            permission.setUserId(user.getUserId());
            if(permissionService.save(permission))return R.success("新增成功！");
        }
        return R.error("未知错误！");
    }

    @GetMapping("/list")
    public R list(){
        int roleId = Integer.parseInt(StpUtil.getRoleList().get(0));
        List<User> userList = userService.getBaseMapper().selectList(new LambdaQueryWrapper<User>()
                .eq(User::getRoleId,RoleConstant.UNDEFINED_INT));
        if(roleId==RoleConstant.FACTORY_MANAGER_INT){
            Long factoryId = permissionService.getFactoryIdsByUserId(
                    userService.getExistByUserName(StpUtil.getLoginId().toString())
                            .getUserId()).get(0);

            List<WorkShop> workShops = workShopService.getBaseMapper().selectList(new LambdaQueryWrapper<WorkShop>()
                    .eq(WorkShop::getFactoryId,factoryId));

            for (WorkShop workShop:workShops){
                List<Permission> permissions = permissionService.getBaseMapper().selectList(new LambdaQueryWrapper<Permission>()
                        .eq(Permission::getId,workShop.getId()));
                for (Permission permission:permissions){
                    User user = userService.getById(permission.getUserId());
                    if(user!=null) {
                        user.setPerName(workShopService.getById(permission.getId()).getName());
                        user.setId(workShop.getId());
                        userList.add(user);
                    }
                }
            }
        }else if(roleId==RoleConstant.BOSS_INT){
            List<Factory> factoryList = factoryService.getBaseMapper().selectList(null);

            for (Factory factory:factoryList){
                List<Permission> permissions = permissionService.getBaseMapper().selectList(new LambdaQueryWrapper<Permission>()
                        .eq(Permission::getFactoryId,factory.getFactoryId()));
                for (Permission permission:permissions){
                    User user = userService.getById(permission.getUserId());
                    if(user!=null) {
                        user.setFactoryId(factory.getFactoryId());
                        user.setPerName(factoryService.getById(permission.getFactoryId()).getFactoryName());
                        userList.add(user);
                    }
                }
            }
        }
        return R.success(userList);
    }

    @SaCheckRole(value = {RoleConstant.FACTORY_MANAGER,RoleConstant.BOSS},mode = SaMode.OR)
    @PostMapping("/deletePermission")
    public R deletePermission(@RequestBody User user){
//        if((StringUtils.isNullOrEmpty(permission.getFactoryName())&&StringUtils.isNullOrEmpty(permission.getName()))
//        |StringUtils.isNullOrEmpty(permission.getUserName()))return R.error("参数不全！");
//
//        permission.setPermissionId(IdUtils.getInstance().NextId());
//
//        User user = userService.getExistByUserName(permission.getUserName());
//
//        if(!StringUtils.isNullOrEmpty(permission.getFactoryName())){
//            user.setRoleId(RoleConstant.FACTORY_MANAGER_INT);
//            userService.updateById(user);
//
//            permission.setFactoryId(factoryService.getBaseMapper().selectOne(new LambdaQueryWrapper<Factory>()
//                    .eq(Factory::getFactoryName,permission.getFactoryName())).getFactoryId());
//
//            permission.setUserId(user.getUserId());
//            if(permissionService.save(permission))return R.success("新增成功！");
//        }else if(!StringUtils.isNullOrEmpty(permission.getName())){
//            user.setRoleId(RoleConstant.WORKSHOP_MANAGER_INT);
//            userService.updateById(user);
//            User userNow = userService.getExistByUserName((String) StpUtil.getLoginId());
//            Long factoryId = permissionService.getFactoryIdsByUserId(userNow.getUserId()).get(0);
//            permission.setId(workShopService.getBaseMapper().selectOne(new LambdaQueryWrapper<WorkShop>()
//                    .eq(WorkShop::getFactoryId,factoryId)
//                    .eq(WorkShop::getName,permission.getName()))
//                    .getId());
//            permission.setUserId(user.getUserId());
//            if(permissionService.save(permission))return R.success("新增成功！");
//        }
//
//        return R.error("未知错误！");

        if((user.getFactoryId()==null&&user.getId()==null)
                |StringUtils.isNullOrEmpty(user.getUserName()))return R.error("参数不全！");

        User userData = userService.getExistByUserName(user.getUserName());

        if(user.getFactoryId()!=null){
            Permission permission = permissionService.getBaseMapper().selectOne(new LambdaQueryWrapper<Permission>()
                    .eq(Permission::getUserId,userData.getUserId())
                    .eq(Permission::getFactoryId,user.getFactoryId()));
            if(permission==null)return R.error("该权限不存在！");
            if(permissionService.deleteFactory(permission,userData))return R.success("删除成功！");

        }else if(user.getId()!=null){
            Permission permission = permissionService.getBaseMapper().selectOne(new LambdaQueryWrapper<Permission>()
                    .eq(Permission::getUserId,userData.getUserId())
                    .eq(Permission::getId,user.getId()));
            if(permission==null)return R.error("该权限不存在！");
            if(permissionService.deleteWorkShop(permission,userData))return R.success("删除成功！");
        }
        return R.error("未知错误！");
    }

}
